<template>
  <div class="commission-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>佣金管理</span>
        </div>
      </template>
      
      <div class="search-box">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="代理名称">
            <el-select v-model="queryParams.agent_id" placeholder="选择代理" clearable>
              <el-option
                v-for="agent in agentOptions"
                :key="agent.id"
                :label="agent.name"
                :value="agent.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="结算状态">
            <el-select v-model="queryParams.status" placeholder="全部状态" clearable>
              <el-option :value="0" label="待结算" />
              <el-option :value="1" label="已结算" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-table v-loading="loading" :data="commissionList">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="agent_name" label="代理名称" />
        <el-table-column prop="order_id" label="订单ID" width="100" />
        <el-table-column prop="amount" label="佣金金额">
          <template #default="scope">
            <span class="amount">¥{{ scope.row.amount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="rate" label="佣金比例">
          <template #default="scope">
            {{ (scope.row.rate * 100).toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column prop="level_name" label="佣金类型" />
        <el-table-column prop="create_time" label="创建时间" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'warning' : 'success'">
              {{ scope.row.status_text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="settle_time" label="结算时间" width="150" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 0"
              type="primary"
              size="small"
              @click="handleSettle(scope.row)"
            >
              结算
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="queryParams.page"
          :page-size="queryParams.per_page"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCommissionList, settleCommission, getAgentList } from '@/api/agents'

const loading = ref(false)
const commissionList = ref([])
const total = ref(0)
const agentOptions = ref([])

const queryParams = reactive({
  page: 1,
  per_page: 10,
  agent_id: '',
  status: ''
})

// 获取佣金列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getCommissionList(queryParams)
    if (res.code === 0) {
      commissionList.value = res.data.items || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取佣金列表失败')
    }
  } catch (error) {
    console.error('获取佣金列表失败', error)
    ElMessage.error('获取佣金列表失败')
  } finally {
    loading.value = false
  }
}

// 获取代理列表
const getAgents = async () => {
  try {
    const res = await getAgentList({ page: 1, per_page: 100 })
    if (res.code === 0) {
      agentOptions.value = res.data.items || []
    }
  } catch (error) {
    console.error('获取代理列表失败', error)
  }
}

// 结算佣金
const handleSettle = (row) => {
  ElMessageBox.confirm(`确认要结算这笔佣金吗？金额: ¥${row.amount.toFixed(2)}`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await settleCommission(row.id)
      if (res.code === 0) {
        ElMessage.success('结算成功')
        getList()
      } else {
        ElMessage.error(res.message || '结算失败')
      }
    } catch (error) {
      console.error('结算失败', error)
      ElMessage.error('结算失败')
    }
  })
}

// 查询
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.agent_id = ''
  queryParams.status = ''
  handleQuery()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 每页条数改变
const handleSizeChange = (val) => {
  queryParams.per_page = val
  queryParams.page = 1
  getList()
}

onMounted(() => {
  getList()
  getAgents()
})
</script>

<style scoped>
.commission-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-box {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.amount {
  color: #f56c6c;
  font-weight: bold;
}
</style> 